package com.surprise;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import weibo4j.Weibo;
import weibo4j.http.AccessToken;

public class WebFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		if (WeiboHolder.getRequestToken() != null) {
			try {
				String verifier = request.getParameter("oauth_verifier");
				if (verifier == null) {
					AccessToken accessToken = (AccessToken) ((HttpServletRequest) request).getSession().getAttribute("accessToken");
					if (accessToken == null) {
						((HttpServletResponse) response).sendRedirect(WeiboHolder.getRequestToken().getAuthorizationURL());
					} else {
						filterChain.doFilter(request, response);
					}
				} else {
					Weibo weibo = WeiboHolder.getWeibo();
					AccessToken accessToken = weibo.getOAuthAccessToken(WeiboHolder.getRequestToken().getToken(), WeiboHolder.getRequestToken().getTokenSecret(), verifier);
					((HttpServletRequest)request).getSession().setAttribute("accessToken", accessToken);
					filterChain.doFilter(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		WeiboHolder.buildWeibo();
	}

}
